package cn.growthgate.fgo.util;

import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;

/**
 * 缓存工具类
 * 
 * @author GrowthGate
 * @since 2019年4月30日
 *
 */
public class CacheUtils {

	private static CacheManager getCacheManager() {
		return SpringUtils.getBean(CacheManager.class);
	}
	
	private static Cache getCache(String name) {
		return getCacheManager().getCache(name);
	}
	
	public static void put(String name, Object key, Object value) {
		Cache cache = getCache(name);
		if (cache != null) {
			cache.put(key, value);
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T get(String name, Object key) {
		Cache cache = getCache(name);
		if (cache == null) {
			return null;
		}
		ValueWrapper valueWrapper = cache.get(key);
		return valueWrapper != null ? (T) valueWrapper.get() : null;
	}
	
	public static void clear(String name) {
		Cache cache = getCache(name);
		if (cache != null) {
			cache.clear();
		}
	}
	
}
